package com.tianyadu.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tianyadu.security.core.properties.SecurityProperties;
import com.tianyadu.security.core.properties.propertieVO.LoginResponseType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @FileName: AuthSuccessHandler
 * @Description: 登录成功回调处理
 * @author: xueyj
 * @create: 2018-12-08 22:16
 */
@Slf4j
@Component
public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    /**
      * @Description: 授权认证成功处理
      * @param:
      * @return:
      * @author:
      * @date:   2018/12/10 17:52
      */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        log.info("登录成功");
        if (LoginResponseType.JSON.equals(securityProperties.getBrowser().getLoginType())) {
            //  设置响应信息的格式及字符编码
            response.setContentType("application/json;charset=UTF-8");
            //  将响应信息写入至response
            response.getWriter().write(objectMapper.writeValueAsString(authentication));
        } else {
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}